package com.example;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DistributeClient {

    private static final int sessionTimeout = 2000;
    private static final String connectString = "Cent7:2181,Cent7-c1:2181,Cent7-c2:2181";
    private ZooKeeper zkClient = null;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        // 1.获取zookeeper连接
        DistributeClient client = new DistributeClient();
        client.getConnection();

        // 2.监听/servers下的子节点的增加和删除
        client.getServerList();

        // 3.启动业务逻辑（睡觉）
        client.business();
    }

    private void getServerList() throws InterruptedException, KeeperException {

        List<String> childrenList = zkClient.getChildren("/servers", true);
        ArrayList<String> servers = new ArrayList<>();

        if (childrenList != null) {
            for (String child : childrenList) {
                byte[] data = zkClient.getData("/servers/" + child, false, null);
                servers.add(new String(data));
            }
        }

        System.out.println(servers.size() == 0 ? "没有数据" : servers);
    }

    private void business() throws InterruptedException {
        // 线程休眠的同时监听仍在进行
        Thread.sleep(Long.MAX_VALUE);

    }

    private void getConnection() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {

            @Override
            public void process(WatchedEvent watchedEvent) {

                try {
                    getServerList();
                } catch (InterruptedException | KeeperException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
